package com.example.toutiao.http


import com.example.toutiao.base.Constants.BASE_URL
import com.example.toutiao.base.Constants.BASE_URL_TEST
import com.example.toutiao.mvp.model.BaseModel
import com.example.toutiao.ui.main.model.MainModel
import com.orhanobut.logger.Logger
import io.reactivex.Observable
import io.reactivex.Observer
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor

import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.*
import java.util.concurrent.TimeUnit
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

object HttpUtils {
    private var mOkhttp: OkHttpClient?=null
    private fun isTest(isTest:Boolean):String=if(isTest) BASE_URL_TEST else BASE_URL
    fun<T> createApi(clazz:Class<T>): T = Retrofit.Builder()
        .baseUrl(isTest(true))
        .client(getClient())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(clazz)
    private fun getClient():OkHttpClient?{
        if(mOkhttp==null){
            mOkhttp = OkHttpClient.Builder()    //builder构造者设计模式
                .connectTimeout(30, TimeUnit.SECONDS) //连接超时时间
                .readTimeout(30, TimeUnit.SECONDS)    //读取超时
                .writeTimeout(30, TimeUnit.SECONDS)  //写超时，也就是请求超时
                .addInterceptor(getInterceptor())
                .build();
        }
        return mOkhttp
    }
    private fun getInterceptor():Interceptor{
        HttpLoggingInterceptor.Logger {
            Logger.json(it)
        }
        return HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
    }

    fun<T> sendHttp(ob: Observable<T>, listener:ResponseListener<T>){

        ob.subscribeOn(Schedulers.io())
            .subscribeOn(AndroidSchedulers.mainThread()) // 在主线程渲染
            .observeOn(AndroidSchedulers.mainThread()) // 在主线程进行
            .subscribe(object:Observer<T>{
                override fun onSubscribe(d: Disposable) {

                }
                override fun onNext(t: T) {
                    listener.onSuccess(t)
                }

                override fun onError(e: Throwable) {
                    listener.onFail(e.message.toString())
                }

                override fun onComplete() {

                }
            })
    }


}